package cn.whdreamblog.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;

public class MyDBUtil {
	public static final String _id = " id ";
	public static final String _FROM =" from ";
	public static final String _WHERE =" where ";
	public static final String _EQUALS =" = ";
	public static final String _OR =" or ";
	public static final String _AND =" and ";
	public static final String _BY =" by ";
	public static final String _DESC =" desc ";
	public static final String _ORDER_BY =" order by ";
	public static final String _SELECT =" select ";
	public static final String _UPDATE =" update ";
	public static final String _SET =" set ";
	private static SessionFactory sessionFactory;
	static {
		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
				.configure() // configures settings from hibernate.cfg.xml
				.build();
		
		try {
			sessionFactory = new MetadataSources(registry).buildMetadata()
					.buildSessionFactory();
		} catch (Exception e) {
			// The registry would be destroyed by the SessionFactory, but we had
			// trouble building the SessionFactory
			// so destroy it manually.
			e.printStackTrace();
			StandardServiceRegistryBuilder.destroy(registry);
		}
	}

	public static SessionFactory getSessionFactory() throws Exception {
		// A SessionFactory is set up once for an application!

		return sessionFactory;
	}
	
	public static void closeSession(Session session,Transaction tx) {
		if(session!=null){
			session.close();
			session=null;
			tx=null;
		}
	}
	public static void rollBack(Transaction tx) {
		if(tx!=null){
			tx.rollback();
			tx=null;
		}
	}
}
